package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Log;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author zwy
 */
@Service(version = "1.0.0")
public class LogApiImpl implements LogApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveLog(Log log) {
        //如果sound对象的id为空,则返回null
        if (log.getUserId() == null) {
            return null;
        }
        log.setId(ObjectId.get());
        log.setLogTime(System.currentTimeMillis());

        this.mongoTemplate.save(log);
        return log.getId().toString();
    }

    @Override
    public List<Log> getLog(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("logTime")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        return this.mongoTemplate.find(query, Log.class);
    }
}
